﻿using JNPF.Basics.Models;
using JNPF.Utils;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace JNPF.Basics.Logic
{
    /// <summary>
    /// 公众号菜单
    /// 版 本：V3.0.0
    /// 版 权：引迈信息技术有限公司（https://www.jnpfsoft.com）
    /// 作 者：JNPF开发平台组
    /// 日 期：2018-09-18 
    /// </summary>
    public class MPMenuBll
    {
        private MPEventContentBll mPEventContentBll = new MPEventContentBll();

        /// <summary>
        /// 列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<MPMenuModel>> GetList()
        {
            try
            {
                var config = await new SysConfigBll().GetInfo("MPConfig");
                var menuList = new List<MPMenuModel>();
                var menuJson = new WeChatMPHelper(config.WX_GZH_APPID, config.WX_GZH_APPSECRET).GetMenu();
                if (!string.IsNullOrEmpty(menuJson))
                {
                    var menuButtonList = JsonHelper.ToList<MPMenuButtonModel>(menuJson);
                    foreach (var menuButton in menuButtonList)
                    {
                        MPMenuModel menuModel = new MPMenuModel();
                        menuModel.Id = Md5Helper.md5(menuButton.name);
                        menuModel.Key = menuButton.key;
                        menuModel.Name = menuButton.name;
                        menuModel.ParentId = "0";
                        menuModel.Type = menuButton.type;
                        menuModel.Url = menuButton.url;
                        menuModel.SortCode = menuButtonList.IndexOf(menuButton);
                        menuList.Add(menuModel);
                        if (menuButton.sub_button != null)
                        {
                            foreach (var menuSubButton in menuButton.sub_button)
                            {
                                MPMenuModel subMenuModel = new MPMenuModel();
                                subMenuModel.Id = Md5Helper.md5(menuSubButton.name);
                                subMenuModel.Key = menuSubButton.key;
                                subMenuModel.Name = menuSubButton.name;
                                subMenuModel.ParentId = menuModel.Id;
                                subMenuModel.Type = menuSubButton.type;
                                subMenuModel.Url = menuSubButton.url;
                                subMenuModel.SortCode = menuButton.sub_button.IndexOf(menuSubButton);
                                menuList.Add(subMenuModel);
                            }
                        }
                    }
                }
                return menuList;
            }
            catch (Exception ex)
            {
                LogFactory.GetLogger().Error(ex);
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 同步
        /// </summary>
        /// <param name="menuList"></param>
        public async Task SyncMenu(List<MPMenuModel> menuList)
        {
            try
            {
                var config = await new SysConfigBll().GetInfo("MPConfig");
                StringBuilder menuJson = new StringBuilder();
                var menuButtonList = new List<MPMenuButtonModel>();
                if (menuList.Count > 0)
                {
                    var menuParentList = menuList.FindAll(m => m.ParentId == "0");
                    foreach (var item in menuParentList)
                    {
                        if (menuList.FindAll(m => m.ParentId == item.Id).Count > 0)
                        {
                            item.Type = "";
                        }
                        else
                        {
                            if (menuList.FindAll(m => m.ParentId == item.Id).Count == 0 && item.Type == "view")
                            {
                                item.Type = "view";
                            }
                            else
                            {
                                item.Type = "click";
                                item.Key = Md5Helper.md5(item.Name);
                            }
                        }
                        MPMenuButtonModel menuButtonModel = new MPMenuButtonModel();
                        menuButtonModel.key = item.Type == "view" ? null : item.Key;
                        menuButtonModel.name = item.Name;
                        menuButtonModel.type = item.Type;
                        menuButtonModel.url = item.Url;
                        if (string.IsNullOrEmpty(item.Type))
                        {
                            var menuSubList = menuList.FindAll(m => m.ParentId == item.Id);
                            var sub_button = new List<MPMenuSubButtonModel>();
                            foreach (var subItem in menuSubList)
                            {
                                if (subItem.Type == "click")
                                {
                                    subItem.Key = Md5Helper.md5(subItem.Name);
                                }
                                MPMenuSubButtonModel menuSubButtonModel = new MPMenuSubButtonModel();
                                menuSubButtonModel.key = subItem.Type == "view" ? null : subItem.Key;
                                menuSubButtonModel.name = subItem.Name;
                                menuSubButtonModel.type = subItem.Type;
                                menuSubButtonModel.url = subItem.Url;
                                sub_button.Add(menuSubButtonModel);
                            }
                            menuButtonModel.sub_button = sub_button;
                        }
                        menuButtonList.Add(menuButtonModel);
                    }
                    menuJson.Append(menuButtonList.ToJson());
                }
                //旧数据防止创建失败回滚到旧数据
                var oldMenuJson = new WeChatMPHelper(config.WX_GZH_APPID, config.WX_GZH_APPSECRET).GetMenu();
                //删除菜单
                new WeChatMPHelper(config.WX_GZH_APPID, config.WX_GZH_APPSECRET).DeleteMenu();
                //创建菜单
                if (!string.IsNullOrEmpty(menuJson.ToString()))
                {
                    var returnObject = new WeChatMPHelper(config.WX_GZH_APPID, config.WX_GZH_APPSECRET).CreateMenu(menuJson.ToString()).ToObject();
                    if (returnObject["errcode"].ToString() != "0")
                    {
                        //回滚老数据
                        new WeChatMPHelper(config.WX_GZH_APPID, config.WX_GZH_APPSECRET).CreateMenu(oldMenuJson.ToObject()["menu"].ToString());
                        throw new Exception(returnObject["errmsg"].ToString());
                    }
                }
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 重复验证（名称）
        /// </summary>
        /// <param name="fullName">名称</param>
        /// <param name="id">键值</param>
        /// <returns></returns>
        public async Task<bool> IsExistByFullName(string fullName, string id)
        {
            try
            {
                var menuList = await this.GetList();
                menuList = menuList.FindAll(m => m.Name == fullName);
                if (!string.IsNullOrEmpty(id))
                {
                    menuList = menuList.FindAll(m => m.Id != id);
                }
                return menuList.Count > 0 ? true : false;
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 创建
        /// </summary>
        /// <param name="model">model</param>
        public async Task Create(MPMenuModel model)
        {
            try
            {
                var entity = new MPEventContentEntity()
                {
                    EventKey = Md5Helper.md5(model.Name),
                    Content = model.Content
                };
                await mPEventContentBll.Create(entity);
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主键</param>
        public async Task Delete(string id)
        {
            try
            {
                var entity = await mPEventContentBll.GetInfo(id);
                if (entity != null)
                {
                    await mPEventContentBll.Delete(entity);
                }
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="id">主键值</param>
        /// <param name="MPMenuModel">model</param>
        public async Task Update(string id, MPMenuModel model)
        {
            try
            {
                var entity = await mPEventContentBll.GetInfo(id);
                if (entity != null)
                {
                    entity.EventKey = model.Key;
                    entity.Content = model.Content;
                    await mPEventContentBll.Update(entity);
                }
            }
            catch (Exception ex)
            {
                throw ExceptionEx.Throw(ex);
            }
        }

    }
}
